<template>
	<div class="wrapper">
	  <header>
		<p>我的订单</p>
	  </header>
  
	  <!-- 未支付订单 -->
	  <h3>未支付订单信息：</h3>
<ul class="order" v-if="orderArr.length > 0">
  <li v-for="item in unpaidOrders" :key="item.orderId">
    <div class="order-info">
      <p>
        {{ item.business?.businessName }}
        <i class="fa fa-caret-down" @click="toggleDetail(item)"></i>
      </p>
      <div class="order-info-right">
        <p>&#165;{{ item.orderTotal }}</p>
        <div class="order-info-right-icon" @click="toPayment(item.orderId)">去支付</div>
        <div class="order-info-right-icon" @click="deleteOrder(item.orderId)">删除</div>
      </div>
    </div>
    <ul class="order-detailet" v-show="item.isShowDetail">
      <li v-for="odItem in getOrderDetails(item.orderId)" :key="odItem.food.foodName">
        <p>{{ odItem.food.foodName }} x {{ odItem.quantity }}</p>
        <p>&#165;{{ odItem.buyPrice * odItem.quantity }}</p>
      </li>
      <li>
        <p>配送费</p>
        <p>&#165;{{ item.business.deliveryPrice }}</p>
      </li>
    </ul>
  </li>
</ul>

  
	  <!-- 已支付订单 -->
	  <h3>已支付订单信息：</h3>
		<ul class="order" v-if="orderArr.length > 0">
		<li v-for="item in paidOrders" :key="item.orderId">
			<div class="order-info">
			<p>
				{{ item.business?.businessName }}
				<i class="fa fa-caret-down" @click="toggleDetail(item)"></i>
			</p>
			<div class="order-info-right">
				<p>&#165;{{ item.orderTotal }}</p>
			</div>
			<div class="order-info-right-icon" @click="deleteOrder(item.orderId)">删除</div>
			</div>
			<ul class="order-detailet" v-show="item.isShowDetail">
			<li v-for="odItem in getOrderDetails(item.orderId)" :key="odItem.food.foodName">
				<p>{{ odItem.food.foodName }} x {{ odItem.quantity }}</p>
				<p>&#165;{{ Math.round(odItem.buyPrice * odItem.quantity * 100)/100 }}</p>
			</li>
			<li>
				<p>配送费</p>
				<p>&#165;{{ item.business.deliveryPrice }}</p>
			</li>
			</ul>
		</li>
		</ul>

	  <ul class="block">
		<p>
		  &nbsp;
		</p>
	  </ul>
  
	  <Footer></Footer>
	</div>
  </template>
  
  <script>
  import { ref, onMounted, computed } from 'vue';
  import Footer from '../components/Footer.vue';
  import { useRouter } from 'vue-router';
  import { getSessionStorage, removeLocalStorage } from '../common.js';
  import axios from 'axios';
  
  export default {
	name: 'OrderList',
	components: { Footer },
	setup() {
	  const router = useRouter();
	  const orderArr = ref([]); // 订单数组
	  const orderDetailetArr = ref([]); //订单明细数组
	  const user = ref(getSessionStorage('user')); // 从 sessionStorage 获取用户信息
  
	  // 获取订单数据
	  const listOrdersByUserId = async () => {
		try {
		  const response = await axios.get(`Orders/userId/${user.value.userId}`);
		  const result = response.data.map(order => ({
			...order,
			isShowDetail: false // 初始化时隐藏订单详情
		  }));
		  orderArr.value = result;

		   // 在获取订单后，依次获取每个订单的订单详情
		   	await Promise.all(
				orderArr.value.map(async (order) => {
				await listOrderDetailetByOrderId(order.orderId);
			})
      );
		} catch (error) {
		  console.error('获取订单数据失败:', error);
		}
	  };

	  // 获取订单明细
	const listOrderDetailetByOrderId = async (orderId) => {
		try {
		const response = await axios.get(`OrderDetailet/orderId/${orderId}`);
		
		// 将当前订单详情合并到 orderDetailetArr 中
		orderDetailetArr.value.push(...response.data);
		} catch (error) {
		console.error('获取订单详情数据失败:', error);
		}

		console.log(orderDetailetArr.value);
	};

	// 根据订单ID筛选对应的订单详情
	const getOrderDetails = (orderId) => {
		return orderDetailetArr.value.filter(odItem => odItem.orderId === orderId);
	};

	  // 切换订单详情的显示状态
	  const toggleDetail = (order) => {
		order.isShowDetail = !order.isShowDetail;
	  };
  
	  // 删除订单
	  const deleteOrder = async (orderId) => {
		if (!confirm('确认删除此订单吗？')) return;
		try {
		  const response = await axios.delete(`Orders/orderId/${orderId}`);
		  if (response.data > 0) {
			orderArr.value = orderArr.value.filter(order => order.orderId !== orderId);
			removeLocalStorage(user.value.userId);
			alert('订单已删除');
		  } else {
			alert('删除失败，请稍后再试');
		  }
		} catch (error) {
		  console.error('删除订单失败:', error);
		  alert('删除失败，请稍后再试');
		}
	  };
  
	  // 跳转到支付页面
	  const toPayment = (orderId) => {
		router.push({ path: '/payment', query: { orderId } });
	  };
  
	  // 在组件挂载时加载订单数据
	  onMounted(() => {
		if (user.value) {
		  listOrdersByUserId();
		} else {
		  console.error('未找到用户信息');
		}
	  });
  
	  // 筛选未支付的订单
	  const unpaidOrders = computed(() => orderArr.value.filter(order => order.orderState === 0));
  
	  // 筛选已支付的订单
	  const paidOrders = computed(() => orderArr.value.filter(order => order.orderState === 1));
  
	  return {
		orderArr,
		orderDetailetArr,
		toggleDetail,
		deleteOrder,
		toPayment,
		unpaidOrders,
		paidOrders,
		getOrderDetails
	  };
	}
  };
  </script>
  
  <style scoped>
  /* 样式保持不变 */
  .wrapper {
	width: 100%;
	height: 100%;
  }
  
  .wrapper header {
	width: 100%;
	height: 12vw;
	background-color: #0097FF;
	color: #fff;
	font-size: 4.8vw;
	position: fixed;
	left: 0;
	top: 0;
	z-index: 1000;
	display: flex;
	justify-content: center;
	align-items: center;
  }
  
  .wrapper h3 {
	margin-top: 12vw;
	box-sizing: border-box;
	padding: 4vw;
	font-size: 4vw;
	font-weight: 300;
	color: #999;
  }
  
  .wrapper .order {
	width: 100%;
  }
  
  .wrapper .order li {
	width: 100%;
  }
  
  .wrapper .order li .order-info {
	box-sizing: border-box;
	padding: 2vw 4vw;
	font-size: 4vw;
	color: #666;
	display: flex;
	justify-content: space-between;
	align-items: center;
  }
  
  .wrapper .order li .order-info .order-info-right {
	display: flex;
  }
  
  .wrapper .order li .order-info .order-info-right .order-info-right-icon {
	background-color: #f90;
	color: #fff;
	border-radius: 3px;
	margin-left: 2vw;
	user-select: none;
	cursor: pointer;
  }
  
  .wrapper .order li .order-detailet {
	width: 100%;
  }
  
  .wrapper .order li .order-detailet li {
	width: 100%;
	box-sizing: border-box;
	padding: 1vw 4vw;
	color: #666;
	font-size: 3vw;
	display: flex;
	justify-content: space-between;
	align-items: center;
  }

  .wrapper .block{
	padding-bottom: 10vw;
  }
  </style>
  